package com.wdciti.sccp.iot.gateway.endpoint.my;

import com.alibaba.fastjson.JSONArray;
import com.wdciti.sccp.iot.gateway.domain.Channel;
import com.wdciti.sccp.iot.gateway.domain.TagPosition;
import com.wdciti.sccp.iot.springvertx.annotation.VerticleBean;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.client.HttpRequest;
import io.vertx.ext.web.client.WebClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;

/**
 * 对梦芯接口，httpclient请求后，按平台格式发MQTT给平台。
 *
 * @author JINWEN
 */
@Slf4j
@VerticleBean(isWorker = false)
public class MexAdapterVerticle extends AbstractVerticle {

    @Value("${mex.http.ip:null}")
    private String mexIp;

    @Value("${mex.http.port:0}")
    private Integer mexPort;

    @Value("${mex.http.host:null}")
    private String mexHost;

    @Value("${mex.http.userName}")
    private String userName;

    @Value("${mex.http.password}")
    private String password;
    private String token;
    private static final String SEND_DATA_BUS_ADDR = "addr:location/now/mex";
    @Resource
    private RedisTemplate redisTemplate;

    private static final String personList = "/gateway-service/api-service/person/listPage";
    private static final String positionCurrent = "/gateway-service/api-service/position/currentList";
    private static final String login = "/gateway-service/auth/login";
    private WebClient webClient;

    private int pageNum = 0;
    private int pageNow = 0;
    private long startTime;

    @Override
    public void start() {

        JsonObject user = JsonObject.of().put("userName", userName).put("password", password).put("source", "API");
        if (token == null) {
            doPostLogin(user);
        } else {
            System.out.println(token);
        }

        vertx.setPeriodic(8000, 5000, hd -> {
            //请求人员实时定位接口
            HttpRequest<Buffer> request = getHttpRequest(positionCurrent);
            request.putHeader("Authorization", token).sendJsonObject(JsonObject.of())    // 梦芯要求不传参数
                    .onSuccess(success -> {
                        //mock数据
//                        JsonArray data = mockData().toJsonObject().getJsonArray("data", JsonArray.of());
                        //log.error("+++++++++++++++++++++" + positionCurrent + "+++++++++++++++++++");
                        //log.info("+++++++++++++++++++++"+  success.body().toString());
                        JsonObject body = success.body().toJsonObject();
                        if (body != null && !body.isEmpty()) {
                            JsonArray data = body.getJsonArray("data", JsonArray.of());
                            data.forEach(i -> sendData((JsonObject) i));
                        }
                    }).onFailure(Throwable::printStackTrace);
        });

        //请求查询人员列表接口放缓存，让平台查
        vertx.setPeriodic(5000, 2000, hd -> {
            if (pageNow == 0) {
                this.startTime = System.currentTimeMillis();
            }
            if (pageNow <= pageNum) {
                pageNow = pageNow + 1;
                requestPersonList(pageNow);
            } else {
                if (System.currentTimeMillis() - this.startTime > 60 * 60 * 1000) {
                    pageNow = 0;
                    redisTemplate.delete("person");
                }
            }
        });
    }

    private void requestPersonList(int i) {
        this.getHttpRequest(personList).putHeader("Authorization", token).sendJsonObject(JsonObject.of()
                .put("pageFlag", "Y")
                .put("pageNum", String.valueOf(i))
                .put("pageSize", "200")).onSuccess(success -> {
            if (success.statusCode() != 200) {
                //log.error("[[ERROR!]]梦芯 system (/auth/login) failed! code={}, msg={}", success.statusCode(), success.statusMessage());
            } else {
                //log.info("----------{}: (page={})----------------", personList, i);
//                            log.info(success.body().toString());
                JsonObject object = success.body().toJsonObject();
                String total = object.getString("total");  //11754
                int totalNum = Integer.parseInt(total);
                this.pageNum = totalNum / 200;
                cachePersonList(object);
            }
        }).onFailure(Throwable::printStackTrace);
    }

    private void cachePersonList(JsonObject result) {
        JSONArray personArray = (JSONArray) redisTemplate.opsForValue().get("person");
        if (personArray == null || personArray.isEmpty()) {
            personArray = new JSONArray();
        }
        JsonArray data = result.getJsonArray("data");
        if (!data.isEmpty()) {
            for (int i = 0; i < data.size(); i++) {
                JsonObject jsonObject = data.getJsonObject(i);
                String cardId = jsonObject.getString("cardId");
                String jobNumber = jsonObject.getString("jobNumber");
                if (cardId == null || jobNumber == null || cardId.isEmpty() || jobNumber.isEmpty()) {
                    continue;
                }
                JsonObject jsonData = JsonObject.of()
                        .put("cardId", Long.parseLong(cardId))
                        .put("tagId", jobNumber);
                personArray.add(String.valueOf(jsonData));
            }
            redisTemplate.opsForValue().set("person", personArray);
        }
    }

    /**
     * 登录
     */
    public void doPostLogin(JsonObject user) {
        this.getHttpRequest(login).sendJsonObject(user).onSuccess(hd -> {
            if (hd.statusCode() == 200) {
                JsonObject object = hd.body().toJsonObject();
                token = object.getJsonObject("data").getString("token");
                //log.info("login mex system success!, token={}", token);
            } else {
                //log.error("[[ERROR!]]梦芯 system (/auth/login) failed! code={}, msg={}", hd.statusCode(), hd.statusMessage());
            }

        }).onFailure(Throwable::printStackTrace);
    }

    /**
     * 发送数据
     */
    private void sendData(JsonObject jsonObject) {
        String acceptTimes = jsonObject.getString("acceptTime", "");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime dateTime = LocalDateTime.parse(acceptTimes, formatter);
        long ts = dateTime.toInstant(ZoneOffset.of("+08:00")).toEpochMilli();
        TagPosition position = new TagPosition();
        position.setAlive(true);
//        String layerHeight = jsonObject.getString("layerHeight")
        position.setHigh(0);
        position.setLongitude(jsonObject.getDouble("longitude"));
        position.setLatitude(jsonObject.getDouble("latitude"));
        position.setTimestamp(ts);
        position.setTagId(jsonObject.getString("jobNumber", ""));
        position.setCardId(jsonObject.getString("cardId", ""));
        position.setChannel(Channel.mex.name());
//only MOCK
        JsonObject object = JsonObject.mapFrom(position);
//        System.out.println("jsonData: " + object);
//        //放缓存
//        vertx.sharedData().getLocalMap(Channel.mex.name() + "_now").put(position.getTagId(), object);
        //发送定位数据
        vertx.eventBus().send(SEND_DATA_BUS_ADDR, object);
    }


    private HttpRequest<Buffer> getHttpRequest(String uri) {
        if (this.webClient == null) {
            this.webClient = WebClient.create(vertx);
        }
        if (!StringUtils.isEmpty(mexHost)) {
            return webClient.post(mexHost, uri);
        } else {
            return webClient.post(mexPort, mexIp, uri);
        }
    }

//    /**
//     * 人员实时定位模拟数据
//     */
//    private Buffer mockData() {
//        String jsonSrtring =
//                "{\n" +
//                        "    \"msg\": \"操作成功\",\n" +
//                        "    \"code\": 200,\n" +
//                        "    \"data\": [\n" +
//                        "        {\n" +
//                        "            \"acceptTime\": \"2023-07-19 16:13:24\",\n" +
//                        "            \"beaconId\": -1,\n" +
//                        "            \"distance\": 2.0,\n" +
//                        "            \"cardId\": 82706845886,\n" +
//                        "            \"cardType\": null,\n" +
//                        "            \"cardTypeName\": null,\n" +
//                        "            \"createTime\": null,\n" +
//                        "            \"personId\": 2,\n" +
//                        "            \"personType\": \"staff\",\n" +
//                        "            \"personTypeName\": \"员工\",\n" +
//                        "            \"personAttribute\": \"/init/蓝帽.png\",\n" +
//                        "            \"personCategory\": \"员工\",\n" +
//                        "            \"staffType\": \"staff\",\n" +
//                        "            \"staffTypeName\": \"员工\",\n" +
//                        "            \"realName\": \"智慧能源-耿\",\n" +
//                        "            \"deptId\": 110543379758977024,\n" +
//                        "            \"postId\": null,\n" +
//                        "            \"personPhoto\": null,\n" +
//                        "            \"deptName\": \"智慧能源事业部\",\n" +
//                        "            \"postName\": null,\n" +
//                        "            \"jobNumber\": \"110101199006280719\",\n" +
//                        "            \"contractorId\": null,\n" +
//                        "            \"contractorName\": null,\n" +
//                        "            \"undisposedAlarmCount\": 0,\n" +
//                        "            \"longitude\": 114.2423391,\n" +
//                        "            \"latitude\": 30.50524134,\n" +
//                        "            \"layerId\": \"北斗大厦-八楼\",\n" +
//                        "            \"layerName\": \"八楼\",\n" +
//                        "            \"layerHeight\": 35,\n" +
//                        "            \"stillStatus\": 1,\n" +
//                        "            \"layerMoveSpeed\": null\n" +
//                        "        },\n" +
//                        "        {\n" +
//                        "            \"acceptTime\": \"2023-07-19 16:13:24\",\n" +
//                        "            \"beaconId\": -1,\n" +
//                        "            \"distance\": 2.0,\n" +
//                        "            \"cardId\": 82706845886,\n" +
//                        "            \"cardType\": null,\n" +
//                        "            \"cardTypeName\": null,\n" +
//                        "            \"createTime\": null,\n" +
//                        "            \"personId\": 2,\n" +
//                        "            \"personType\": \"staff\",\n" +
//                        "            \"personTypeName\": \"员工\",\n" +
//                        "            \"personAttribute\": \"/init/蓝帽.png\",\n" +
//                        "            \"personCategory\": \"员工\",\n" +
//                        "            \"staffType\": \"staff\",\n" +
//                        "            \"staffTypeName\": \"员工\",\n" +
//                        "            \"realName\": \"智慧能源-耿\",\n" +
//                        "            \"deptId\": 110543379758977024,\n" +
//                        "            \"postId\": null,\n" +
//                        "            \"personPhoto\": null,\n" +
//                        "            \"deptName\": \"智慧能源事业部\",\n" +
//                        "            \"postName\": null,\n" +
//                        "            \"jobNumber\": \"1131300424180039680\",\n" +
//                        "            \"contractorId\": null,\n" +
//                        "            \"contractorName\": null,\n" +
//                        "            \"undisposedAlarmCount\": 0,\n" +
//                        "            \"longitude\": 114.55733913,\n" +
//                        "            \"latitude\": 30.48824134,\n" +
//                        "            \"layerId\": \"北斗大厦-八楼\",\n" +
//                        "            \"layerName\": \"八楼\",\n" +
//                        "            \"layerHeight\": 35,\n" +
//                        "            \"stillStatus\": 1,\n" +
//                        "            \"layerMoveSpeed\": null\n" +
//                        "        }\n" +
//                        "    ]\n" +
//                        "}";
//        return Buffer.buffer(jsonSrtring);
//    }

}
